package net.mgsx.product.t2m.modisco.tools;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.gmt.modisco.java.ASTNode;
import org.eclipse.gmt.modisco.java.Comment;
import org.eclipse.gmt.modisco.java.Javadoc;
import org.eclipse.gmt.modisco.java.TagElement;

public class ModiscoUtils {
	
	private static Logger logger; // NOPMD : logger can be overrided for junit tests
	
	/**
	 * @return the logger
	 */
	public static final Logger getLogger() {
		if(logger == null){
			logger = new LoggerModiscoLoggerBridge();
		}
		return logger;
	}
	/**
	 * @param logger the logger to set
	 */
	public static final void setLogger(Logger logger) {
		ModiscoUtils.logger = logger;
	}

	@SuppressWarnings("unchecked")
	public static <T extends EObject> T getOwner(EObject object, Class<? extends EObject> type){
		if(object != null){
			if(type.isInstance(object)){
				return (T)object;
			}
			return getOwner(object.eContainer(), type);
		}
		return null;
	}
	@SuppressWarnings("unchecked")
	public static <T extends EObject> Collection<T> getElements(EObject object, Class<? extends T> type){
		List<T> lst = new ArrayList<T>();
		for(TreeIterator<EObject> ite =  object.eAllContents() ; ite.hasNext() ; ){
			EObject element = ite.next();
			if(type.isInstance(element)){
				lst.add((T)element);
			}
		}
		return lst;
	}
	@SuppressWarnings("unchecked")
	public static <T extends EObject> Collection<T> getNonProxyElements(EObject object, Class<? extends T> type){
		List<T> lst = new ArrayList<T>();
		for(TreeIterator<EObject> ite =  object.eAllContents() ; ite.hasNext() ; ){
			EObject element = ite.next();
			if(type.isInstance(element) && element instanceof ASTNode && QualityUtils.isNotProxy((ASTNode)element)){
				lst.add((T)element);
			}
		}
		return lst;
	}
	public static String formatMessage(String message, ASTNode context){
		return message  + " for " + getPath(context) + " in file " + context.getOriginalCompilationUnit().getOriginalFilePath();
	}
	public static String getPath(EObject context){
		return context == null ? "" : getPath(context.eContainer()) + "/" + context.eClass().getName();
	}
	
	/**
	 * TODO comment xdoclet style ...
	 * @param e
	 * @return
	 */
	public static boolean isMarked(ASTNode e){
		for(Comment c : e.getComments()){
			if(c instanceof Javadoc){
				for(TagElement tag : ((Javadoc) c).getTags()){
					if("@mgsx.mod".equals(tag.getTagName())){
						return true;
					}
				}
			}
		}
		return false;
	}

}
